// 自定义Cypress命令

// 登录相关命令
Cypress.Commands.add('login', (email = 'admin@example.com', password = 'admin123') => {
  cy.session([email, password], () => {
    cy.visit('/login');
    cy.get('[data-cy="email-input"]').type(email);
    cy.get('[data-cy="password-input"]').type(password);
    cy.get('[data-cy="login-button"]').click();
    cy.url().should('not.include', '/login');
  });
});

// 模态框操作命令
Cypress.Commands.add('confirmModal', () => {
  cy.get('.ant-modal-confirm .ant-btn-primary').click();
});

Cypress.Commands.add('cancelModal', () => {
  cy.get('.ant-modal-confirm .ant-btn-default').click();
});

// 表格操作命令
Cypress.Commands.add('searchInTable', (searchTerm) => {
  cy.get('[data-cy="search-input"]').type(searchTerm);
  cy.get('[data-cy="search-button"]').click();
});

Cypress.Commands.add('refreshTable', () => {
  cy.get('[data-cy="refresh-button"]').click();
});

// 分页操作命令
Cypress.Commands.add('goToPage', (pageNumber) => {
  cy.get('.ant-pagination-item').contains(pageNumber.toString()).click();
});

// 表单操作命令
Cypress.Commands.add('fillForm', (formData) => {
  Object.entries(formData).forEach(([key, value]) => {
    const field = cy.get(`[data-cy="${key}-field"]`);
    if (field.find('select').length > 0) {
      field.find('select').select(value);
    } else if (field.find('input[type="checkbox"]').length > 0) {
      field.find('input[type="checkbox"]').check(value);
    } else if (field.find('input[type="radio"]').length > 0) {
      field.find(`input[type="radio"][value="${value}"]`).check();
    } else {
      field.find('input, textarea').type(value);
    }
  });
});

// 等待命令
Cypress.Commands.add('waitForApi', (alias) => {
  cy.wait(`@${alias}`);
});

Cypress.Commands.add('waitForLoading', () => {
  cy.get('.ant-spin').should('not.exist');
});

// 断言命令
Cypress.Commands.add('shouldHaveSuccessMessage', (message) => {
  cy.get('.ant-message-success').should('contain', message);
});

Cypress.Commands.add('shouldHaveErrorMessage', (message) => {
  cy.get('.ant-message-error').should('contain', message);
});

Cypress.Commands.add('shouldHaveTableRow', (data) => {
  cy.get('.ant-table-tbody tr').should('contain', data);
});

Cypress.Commands.add('shouldNotHaveTableRow', (data) => {
  cy.get('.ant-table-tbody tr').should('not.contain', data);
});

// 菜单导航命令
Cypress.Commands.add('navigateTo', (menuText) => {
  cy.get('.ant-menu-item').contains(menuText).click();
});

// 标签页操作命令
Cypress.Commands.add('switchTab', (tabName) => {
  cy.get('.ant-tabs-tab').contains(tabName).click();
});

// 文件上传命令
Cypress.Commands.add('uploadFile', (selector, fileName, mimeType) => {
  cy.get(selector).then((subject) => {
    cy.fixture(fileName, 'base64').then((content) => {
      const blob = Cypress.Blob.base64StringToBlob(content, mimeType);
      const file = new File([blob], fileName, { type: mimeType });
      const dataTransfer = new DataTransfer();
      dataTransfer.items.add(file);
      subject[0].files = dataTransfer.files;
      cy.wrap(subject).trigger('change', { force: true });
    });
  });
});

// 日期选择器命令
Cypress.Commands.add('selectDate', (selector, date) => {
  cy.get(selector).click();
  cy.get('.ant-picker-cell-inner').contains(date).click();
});

// 时间选择器命令
Cypress.Commands.add('selectTime', (selector, time) => {
  cy.get(selector).click();
  cy.get('.ant-picker-time-panel-cell-inner').contains(time).click();
});

// 范围滑块命令
Cypress.Commands.add('setSliderRange', (selector, min, max) => {
  cy.get(selector).as('slider');
  cy.get('@slider').find('.ant-slider-handle').first().invoke('attr', 'style', 'left: 0%');
  cy.get('@slider').find('.ant-slider-handle').last().invoke('attr', 'style', 'left: 100%');
});

// 树形控件命令
Cypress.Commands.add('expandTreeNode', (nodeText) => {
  cy.get('.ant-tree-node-content-wrapper').contains(nodeText).click();
});

Cypress.Commands.add('selectTreeNode', (nodeText) => {
  cy.get('.ant-tree-node-content-wrapper').contains(nodeText).click();
});

// 标签操作命令
Cypress.Commands.add('addTag', (tagText) => {
  cy.get('.ant-input').type(tagText);
  cy.get('.ant-select-dropdown-item').contains(tagText).click();
});

Cypress.Commands.add('removeTag', (tagText) => {
  cy.get('.ant-tag').contains(tagText).find('.ant-tag-close-icon').click();
});

// 通知验证命令
Cypress.Commands.add('shouldShowNotification', (type, message) => {
  cy.get(`.ant-message-${type}`).should('contain', message);
});

// 网络请求拦截
Cypress.Commands.add('interceptApi', (method, url, response) => {
  cy.intercept(method, url, response).as(`${method}-${url}`);
});

// 等待网络响应
Cypress.Commands.add('waitForResponse', (alias) => {
  cy.wait(`@${alias}`);
});

// 验证API调用
Cypress.Commands.add('shouldHaveMadeApiCall', (alias) => {
  cy.get(`@${alias}`).should('exist');
});

// 获取API响应数据
Cypress.Commands.add('getApiResponse', (alias) => {
  cy.get(`@${alias}`).its('response.body');
});

// 性能测试命令
Cypress.Commands.add('measurePerformance', (actionName, callback) => {
  cy.window().then((win) => {
    const startTime = performance.now();
    callback();
    const endTime = performance.now();
    const duration = endTime - startTime;
    cy.log(`${actionName} took ${duration}ms`);
    cy.wrap(duration).as(`${actionName}Duration`);
  });
});

// 验证页面标题
Cypress.Commands.add('shouldHavePageTitle', (title) => {
  cy.title().should('include', title);
});

// 验证URL包含特定路径
Cypress.Commands.add('shouldHaveUrl', (path) => {
  cy.url().should('include', path);
});

// 验证页面元素可见性
Cypress.Commands.add('shouldElementBeVisible', (selector) => {
  cy.get(selector).should('be.visible');
});

Cypress.Commands.add('shouldElementNotBeVisible', (selector) => {
  cy.get(selector).should('not.be.visible');
});

// 验证元素禁用状态
Cypress.Commands.add('shouldElementBeDisabled', (selector) => {
  cy.get(selector).should('be.disabled');
});

Cypress.Commands.add('shouldElementBeEnabled', (selector) => {
  cy.get(selector).should('not.be.disabled');
});

// 验证表单验证错误
Cypress.Commands.add('shouldHaveFormError', (fieldSelector, errorMessage) => {
  cy.get(fieldSelector).parents('.ant-form-item')
    .find('.ant-form-item-explain')
    .should('contain', errorMessage);
});

// 清除表单
Cypress.Commands.add('clearForm', () => {
  cy.get('input, textarea').clear();
  cy.get('select').each(($select) => {
    cy.wrap($select).select('');
  });
});

// 重置表单
Cypress.Commands.add('resetForm', () => {
  cy.get('[data-cy="reset-button"]').click();
});

// 等待动画完成
Cypress.Commands.add('waitForAnimations', () => {
  cy.wait(300); // 等待CSS动画完成
});

// 获取当前环境
Cypress.Commands.add('getEnvironment', () => {
  return Cypress.env('environment') || 'development';
});

// 验证响应式布局
Cypress.Commands.add('testResponsiveLayout', (breakpoints) => {
  breakpoints.forEach((breakpoint) => {
    cy.viewport(breakpoint.width, breakpoint.height);
    cy.log(`Testing viewport: ${breakpoint.width}x${breakpoint.height}`);
    cy.get('.ant-layout').should('be.visible');
  });
});

// 模拟键盘快捷键
Cypress.Commands.add('pressKey', (key) => {
  cy.get('body').type(`{${key}}`);
});

// 模拟鼠标悬停
Cypress.Commands.add('hover', (selector) => {
  cy.get(selector).trigger('mouseover');
});

// 模拟鼠标离开
Cypress.Commands.add('unhover', (selector) => {
  cy.get(selector).trigger('mouseout');
});

// 验证工具提示
Cypress.Commands.add('shouldHaveTooltip', (selector, tooltipText) => {
  cy.get(selector).trigger('mouseover');
  cy.get('.ant-tooltip').should('contain', tooltipText);
  cy.get(selector).trigger('mouseout');
});

// 验证下拉菜单
Cypress.Commands.add('shouldHaveDropdown', (selector, options) => {
  cy.get(selector).click();
  options.forEach(option => {
    cy.get('.ant-dropdown-menu-item').should('contain', option);
  });
});

// 选择下拉菜单项
Cypress.Commands.add('selectDropdownItem', (selector, itemText) => {
  cy.get(selector).click();
  cy.get('.ant-dropdown-menu-item').contains(itemText).click();
});